//actions = {increment(){return {type:'INCREMENT'}},decrement(){return {type:'DECREMENT'}}}
//boundActions = {increment(){return dispatch({type:'INCREMENT'})},decrement(){return dispatch({type:'DECREMENT'})}}
import {Action, AnyAction,Dispatch} from './';

export interface ActionCreator<A extends Action = AnyAction> {
    (...args: Array<any>): A;
}

export interface ActionCreatorsMapObject<A extends Action = AnyAction> {
    [key: string]: ActionCreator<A>;
}

export default function bindActionCreators<A extends Action,M extends ActionCreatorsMapObject<A>>(actions: any,dispatch: Dispatch) {
  const boundActionCreators: Record<string,any> = {};

  for(const key in actions) {
    const actionCreator = actions[key];
    if(typeof actionCreator === 'function'){
      boundActionCreators[key] = bindActionCreator(actionCreator,dispatch)
    }
  }

  return boundActionCreators;
};

function bindActionCreator(actionCreator: any, dispatch: any): any {
  return function (this: any, ...args: Array<any>) {
    return dispatch(actionCreator.apply(this/*← 谁调用该方法就是谁 这里 this并不重要*/, args));
  };
}
